package com.tan.cwp.controller;

import com.tan.cwp.config.Constant;
import com.tan.cwp.util.PropertiesUtil;
import com.tan.cwp.util.WxUtil;
import com.tan.cwp.wechataes.WXBizMsgCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("/verify")
public class VerifyController {
    Logger logger = LoggerFactory.getLogger(VerifyController.class);

    /**
     * 验证通用开发参数
     */
    @RequestMapping(value = "callback_verify.do" ,method = RequestMethod.GET)
    public void doGetValid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        // 如果是刷新，需返回原echostr
        String echostr = request.getParameter("echostr");

        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Constant.TOKEN, Constant.EncodingAESKey, Constant.CorpID);

        String sEchoStr=""; //需要返回的明文
        PrintWriter out;
        try {
            sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp,
                    nonce, echostr);

            // 验证URL成功，将sEchoStr返回
            out = response.getWriter();
            out.print(sEchoStr);
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
    }

    /**
     * 刷新 ticket
     */
    @RequestMapping(value = "callback_verify.do" ,method = RequestMethod.POST)
    public String doPostValid(HttpServletRequest request) throws Exception {

        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        String type = request.getParameter("type");

        String id = "";

        // 访问应用和企业回调传不同的ID
        if(type.equals("data")){
            id = Constant.CorpID;
        } else {
            id = Constant.SuiteID;
        }



        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Constant.TOKEN, Constant.EncodingAESKey, id);

        String postData="";   // 密文，对应POST请求的数据
        //1.获取加密的请求消息：使用输入流获得加密请求消息postData
        ServletInputStream in = request.getInputStream();
        BufferedReader reader =new BufferedReader(new InputStreamReader(in));

        String tempStr="";   //作为输出字符串的临时串，用于判断是否读取完毕
        while(null!=(tempStr=reader.readLine())){
            postData+=tempStr;
        }

        String suiteXml=wxcpt.DecryptMsg( msg_signature, timestamp, nonce, postData);
        logger.info("suiteXml: " + suiteXml);

        Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
        if(suiteMap.get("SuiteTicket") != null) {
            PropertiesUtil.setProperty("suite_ticket", (String) suiteMap.get("SuiteTicket"));
        } else if(suiteMap.get("AuthCode") != null){
            PropertiesUtil.setProperty("auth_code", (String) suiteMap.get("AuthCode"));
        }

        String success = "success";
        return success;
    }


}
